package com.example.demo4

import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.demo4.model.Card
import com.example.demo4.model.CardMatchingGame
import java.io.ObjectInputStream
import java.io.ObjectOutputStream

class ThreeCardGameFragment : Fragment() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var tvScore: TextView
    private lateinit var btnReset: Button

    private lateinit var game: CardMatchingGame
    private lateinit var adapter: CardAdapter
    private var cardCount = 24

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_game, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews(view)
        loadData()
        setupListeners()
    }

    private fun initViews(view: View) {
        recyclerView = view.findViewById(R.id.recyclerViewCards)
        tvScore = view.findViewById(R.id.tvScore)
        btnReset = view.findViewById(R.id.btnReset)
    }

    private fun loadData() {
        try {
            val input = requireActivity().openFileInput("three_card_game")
            val objectInputStream = ObjectInputStream(input)
            game = objectInputStream.readObject() as CardMatchingGame
            objectInputStream.close()
            input.close()
        } catch (e: Exception) {
            e.printStackTrace()
            // 文件不存在或读取失败，创建新游戏（3张牌匹配模式）
            game = CardMatchingGame(cardCount, 3)
        }
        updateUI()
    }

    private fun saveData() {
        try {
            val output = requireActivity().openFileOutput("three_card_game", android.content.Context.MODE_PRIVATE)
            val objectOutputStream = ObjectOutputStream(output)
            objectOutputStream.writeObject(game)
            objectOutputStream.close()
            output.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun setupListeners() {
        btnReset.setOnClickListener {
            game.reset()
            updateUI()
        }
    }

    private fun updateUI() {
        val cards = mutableListOf<Card>()
        for (i in 0 until game.count) {
            cards.add(game.cardAtIndex(i))
        }

        val spanCount = 4
        val layoutManager = GridLayoutManager(requireContext(), spanCount)
        layoutManager.orientation = GridLayoutManager.VERTICAL
        recyclerView.layoutManager = layoutManager

        // 移除之前的ItemDecoration
        for (i in recyclerView.itemDecorationCount - 1 downTo 0) {
            recyclerView.removeItemDecorationAt(i)
        }

        adapter = CardAdapter(cards) { index ->
            onCardClicked(index)
        }
        recyclerView.adapter = adapter

        tvScore.text = String.format("得分：%d", game.score)
    }

    private fun onCardClicked(index: Int) {
        if (index >= game.count) {
            return
        }

        val card = game.cardAtIndex(index)
        if (card.isMatched) {
            return
        }

        // 检查当前已选中的卡牌数量
        val chosenCards = (0 until game.count)
            .map { game.cardAtIndex(it) }
            .filter { it.isChosen && !it.isMatched }
        
        // 如果已经有2张卡牌被选中，这是第三张，需要延迟处理
        if (chosenCards.size == 2) {
            // 先翻开当前卡牌
            card.isChosen = true
            updateCardsUI()
            
            // 禁用点击
            recyclerView.isEnabled = false
            
            // 延迟1秒后处理匹配结果
            recyclerView.postDelayed({
                // 重置卡牌状态
                card.isChosen = false
                
                // 执行游戏逻辑
                game.chooseCardAtIndex(index)
                updateCardsUI()
                tvScore.text = String.format("得分：%d", game.score)
                saveData()
                
                // 恢复点击
                recyclerView.isEnabled = true
            }, 1000)
        } else {
            // 第一张或第二张卡牌，直接处理
            game.chooseCardAtIndex(index)
            updateCardsUI()
            tvScore.text = String.format("得分：%d", game.score)
            saveData()
        }
    }
    
    private fun updateCardsUI() {
        val cards = mutableListOf<Card>()
        for (i in 0 until game.count) {
            cards.add(game.cardAtIndex(i))
        }
        adapter.updateCards(cards)
    }

    override fun onStop() {
        super.onStop()
        saveData()
    }

    companion object {
        @JvmStatic
        fun newInstance(): ThreeCardGameFragment {
            return ThreeCardGameFragment()
        }
    }
}
